package org.fengdi.order.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.seata.spring.annotation.GlobalTransactional;
import org.fengdi.order.entity.AccountServerRes;
import org.fengdi.order.entity.Order;
import org.fengdi.order.feign.client.AccountClient;
import org.fengdi.order.feign.client.StorageClient;
import org.fengdi.order.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Objects;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    AccountClient accountClient;

    @Autowired
    StorageClient storageClient;

    // 创建订单
    @Override
    @GlobalTransactional
    public void createOrder(Order order) throws RuntimeException{
        Logger logger = Logger.getLogger(OrderServiceImpl.class);
        this.baseMapper.insertOrder(order); // 创建订单信息
        //TODO 调用账户服务扣款
        logger.info("开始扣款");
        try {
            boolean res = this.accountClient.decreaseMoney(order.getUserId(), order.getMoney());
            if(!res) {
                logger.error("扣款失败");
                throw new RuntimeException("扣款失败");
            }
        }catch (RuntimeException e){
            logger.error(e);
            throw e;
        }

        // TODO 调用库存服务减少库存
        logger.info("开始减少库存");
        try {
            boolean res = this.storageClient.decreaseStorage(order.getCommodityCode(), order.getCount());
            if(!res) {
                logger.error("扣库存失败");
                throw new RuntimeException("扣库存失败");
            }
        }catch (RuntimeException e){
            logger.error(e);
            throw e;
        }
    }
}
